import Vue from 'vue'
import Router from 'vue-router'
import MainLayout from '../components/layout/MainLayout.vue'
import Dashboard from '../views/Dashboard.vue'
import Products from '../views/Products.vue'
import Orders from '../views/Orders.vue'
import Staff from '../views/Staff.vue'
import Inventory from '../views/Inventory.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import OperationLog from '../views/OperationLog.vue'
import Forbidden from '../views/403.vue'
import UserProfile from '../views/UserProfile.vue'
import NotificationCenter from '../views/NotificationCenter.vue'
import UserManage from '../views/UserManage.vue'
import SystemSettings from '../views/SystemSettings.vue'
import HelpCenter from '../views/HelpCenter.vue'
import { hasRoutePermission } from '../config/permissions'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/403', component: Forbidden },
    {
      path: '/',
      component: MainLayout,
      children: [
        { path: '', redirect: '/dashboard' },
        { path: 'dashboard', name: 'Dashboard', component: Dashboard },
        { path: 'products', name: 'Products', component: Products },
        { path: 'orders', name: 'Orders', component: Orders },
        { path: 'staff', name: 'Staff', component: Staff },
        { path: 'inventory', name: 'Inventory', component: Inventory },
        { path: 'operation-log', name: 'OperationLog', component: OperationLog },
        { path: 'profile', name: 'UserProfile', component: UserProfile },
        { path: 'notification', name: 'NotificationCenter', component: NotificationCenter },
        { path: 'user-manage', name: 'UserManage', component: UserManage },
        { path: 'settings', name: 'SystemSettings', component: SystemSettings },
        { path: 'help', name: 'HelpCenter', component: HelpCenter }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('isLogin') === '1'
  const userRole = localStorage.getItem('userRole')
  
  // 未登录且不是登录/注册页面,跳转到登录页
  if (to.path !== '/login' && to.path !== '/register' && !isLogin) {
    next('/login')
    return
  }
  
  // 已登录但访问登录/注册页面,跳转到首页
  if ((to.path === '/login' || to.path === '/register') && isLogin) {
    next('/')
    return
  }
  
  // 检查路由权限
  if (isLogin && !hasRoutePermission(userRole, to.path)) {
    next('/403') // 跳转到无权限页面
    return
  }
  
  next()
})

export default router
